"use strict"

/**
 * Web服务，提供web服务支持
 * 
 */

var express = require("express");
var cons = require("consolidate");
var q = require("q");
var db = require("../db");
var app = express();
var session = require('express-session');
var dateFormat = require('dateformat');
var bodyParser = require('body-parser');

// view parser engine
app.engine("html", cons.swig);
app.set("view engine", "html");
app.set("views", __dirname + "/pages");

// set session
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));

//static files(eg. css or js or images)
app.use("/static", express.static(__dirname + "/static"));

// form body parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

var requireAuthentication = function (req, res, next) {
    if (!req.session.user_id) res.redirect("/login");
    else next();
};

/**
 * Routers auto scan
 */

var controllers = require("fs").readdirSync(__dirname);

for (var i = 0, j = controllers.length; i < j; i++) {
    var name = controllers[i];
    if (!/.*json$/.test(name) && name != "main.js" && /.*\.js/.test(name)) {
        var controller = require("./" + name);
        var needAuth = controller.needAuth;
        for (var router in controller) {
            var obj = controller[router];
            if (router == "needAuth") {
                continue;
            }
            if (needAuth)
                app.all(router, requireAuthentication);
            if (typeof (obj) == "function") {
                app.get(router, obj);
            } else {
                var getFn = obj.get;
                if (getFn) {
                    app.get(router, getFn);
                }
                var postFn = obj.post;
                if (postFn) {
                    app.post(router, urlencodedParser, postFn);
                }
            }
        }
    }
}


app.start = function () {
    var server = app.listen(3000, function () {
        console.log("server is started. port is %d", server.address().port);
    });
};

exports = module.exports = app;